package com.wanrue.tcc.admin.etl;

import com.wanrue.tcc.admin.entity.Transaction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class JdbcImport implements DataImport {

    private String name;

    private String tableName;

    private JdbcTemplate jdbcTemplate;

    public JdbcImport(String name, String tableName, DataSource dataSource) {
        this.name = name;
        this.tableName = tableName;
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public List<Transaction> loadAll() {
        String sql = "SELECT GLOBAL_TX_ID, BRANCH_QUALIFIER, DOMAIN,PARTNER_STR, STATUS, TYPE, COUNT, VERSION, RESULT, CREATE_TIME, UPDATE_TIME  FROM " + tableName;
        List<Transaction> list = jdbcTemplate.query(sql, new TransactionMapper());
        return list;
    }

    @Override
    public int update(Transaction t) {
        int resRow = 0;
        try {
            t.setUpdateTime(new Date());
            String sql = "UPDATE " + tableName + " SET STATUS=?,RESULT = ?,VERSION = VERSION + 1,COUNT = ?,UPDATE_TIME=? WHERE GLOBAL_TX_ID = ? AND BRANCH_QUALIFIER = ?  AND DOMAIN = ? AND VERSION=?";
            resRow = jdbcTemplate.update(sql, ps -> {
                ps.setInt(1, t.getStatus());
                ps.setInt(2, t.getResult());
                ps.setInt(3, t.getCount());
                ps.setTimestamp(4, new java.sql.Timestamp(t.getUpdateTime().getTime()));
                ps.setString(5, t.getGlobalId());
                ps.setString(6, t.getBranchId());
                ps.setString(7, t.getDomain());
                ps.setLong(8, t.getVersion());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resRow;
    }

    @Override
    public void destroy() {

    }

    class TransactionMapper implements RowMapper<Transaction> {
        @Override
        public Transaction mapRow(ResultSet r, int i) throws SQLException {
            Transaction transaction = new Transaction();
            transaction.setGlobalId(r.getString("GLOBAL_TX_ID"));
            transaction.setBranchId(r.getString("BRANCH_QUALIFIER"));
            transaction.setDomain(r.getString("DOMAIN"));
            transaction.setPartner(r.getString("PARTNER_STR"));
            transaction.setStatus(r.getInt("STATUS"));
            transaction.setType(r.getInt("TYPE"));
            transaction.setCount(r.getInt("COUNT"));
            transaction.setVersion(r.getInt("VERSION"));
            transaction.setResult(r.getInt("RESULT"));
            transaction.setCreateTime(r.getTimestamp("CREATE_TIME"));
            transaction.setUpdateTime(r.getTimestamp("UPDATE_TIME"));
            return transaction;
        }

    }
}

